<?php

// ==============================================================================
//
// This file is part of the WelSpeak.
//
// Create by Welfony Support <support@welfony.com>
// Copyright (c) 2012-2014 welfony.com
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
// ==============================================================================

function sendResponse($data = array()) {
    global $app;

    $app->response()->body(json_encode($data));
    $app->stop();
}

function getDataFromRequestWithJsonFormat() {
    global $app;

    $reqBody = $app->request->getBody();
    $arrData = json_decode($reqBody, true);
    if($arrData === null) {
        $app->response->setStatus(400);
        sendResponse(array('message' => 'Problems parsing JSON'));
    }

    return $arrData;
}

function sendInvalidFieldResult($resource, $field, $code) {
    global $app;

    $rst = array(
        'message' => 'Validation Failed',
        'errors' => array()
    );
    if ($resource) {
        $rst['errors']['resource'] = $resource;
    }
    if ($field) {
        $rst['errors']['field'] = $field;
    }
    if ($code) {
        $rst['errors']['code'] = $code;
    }

    $app->response->setStatus(422);
    sendResponse($rst);
}

function sendOperationFailedResult($resource) {
    global $app;

    $rst = array(
        'message' => 'Operation Failed',
        'errors' => array()
    );
    if ($resource) {
        $rst['errors']['resource'] = $resource;
    }

    $app->response->setStatus(500);
    sendResponse($rst);
}

function getImageFileType($fileContent) {
    $format = '';

    if (substr($fileContent, 0, 3) == "\xFF\xD8\xFF") {
        $format = 'jpg';
    } elseif (substr($fileContent, 0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") {
        $format = 'png';
    }

    return $format;
}

function getImageFromUrl($url, $targetPath = null) {
    $ch = curl_init($url);

    if ($targetPath) {
        $fp = fopen($targetPath, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
    }

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $return = curl_exec($ch);
    curl_close($ch);

    if ($targetPath) {
        fclose($fp);
    }

    return $return;
}